﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iOak.Business.Resumes;
using System.Transactions;
using iOak.Domain.Resumes;
using iOak.Core;
using System.IO;
using System.Globalization;
using iOak.Business.Campaigns;

namespace iOak.Web.Popups
{
    public partial class PopupAddResumeImage : BasePage
    {
        private static readonly AttachmentService itemAttachmentService = new AttachmentService();
        private static readonly CampaignService itemCampaignService = new CampaignService();

        #region 选择的文件列表(Choose the file list)
        /// <summary>
        /// 选择的文件列表(Choose the file list)
        /// </summary>
        private HttpFileCollection CurrentFile
        {
            get
            {
                return Session["CurrentFiles"] as HttpFileCollection;
            }
            set
            {
                Session["CurrentFiles"] = value;
            }
        }
        #endregion

        private bool ReadOnly
        {
            get
            {
                if (Request.QueryString["ReadOnly"] != null)
                {
                    return bool.Parse(Request.QueryString["ReadOnly"]);
                }
                else
                {
                    return false;
                }
            }
        }

        #region 画面初始化

        /// <summary>
        /// 画面初始化

        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                hidResumeId.Value = Request.QueryString["ResumeId"];
                hidcampaignId.Value = Request.QueryString["campaignId"];
                if (!string.IsNullOrWhiteSpace(hidcampaignId.Value))
                {
                    var item = itemCampaignService.Retrieve(new Guid(hidcampaignId.Value));
                    hidSelectedAttaches.Value = item.SelectedAttaches;
                }
                if (ReadOnly)
                {
                    divActiveList.Style.Add("display", "none");
                    ResumeDetailService resumeDetailService = new ResumeDetailService();
                    var resumeDetailInfo = resumeDetailService.GetListByResumeId(Guid.Parse(hidResumeId.Value));
                    var userName = resumeDetailInfo.FirstOrDefault(m => m.Key.Equals("UserName"));
                    lblName.InnerText = userName.ValueString;
                }
                else
                {
                    divName.Style.Add("display", "none");
                }
                SearchList();
            }

            // 清空控件
            textBoxDisplayOrder.Text = string.Empty;
            textBoxDescription.Text = string.Empty;
            textBoxPageNumber.Text = string.Empty;
        }
        #endregion

        #region 检索绑定数据
        /// <summary>
        /// 检索绑定数据
        /// </summary>
        private void SearchList()
        {
            var bindList = itemAttachmentService.SearchByResumeId(new Guid(hidResumeId.Value));

            // 第一次添加默认添加数据
            if (!string.IsNullOrEmpty(hidSelectedAttaches.Value))
            {
                // 隐藏按钮
                buttonSave.Visible = true;
                buttonUpload.Visible = true;
                button1.Visible = false;
                buttonDelete.Visible = true;

                if (bindList.Count == 0)
                {
                    using (TransactionScope ts = new TransactionScope())
                    {
                        var nameList = hidSelectedAttaches.Value.Split(';');
                        foreach (var name in nameList)
                        {
                            // 保存基本信息
                            var itemfile = new Attachement();
                            itemfile.AttachmentId = Guid.NewGuid();
                            itemfile.Brief = string.Empty;
                            itemfile.Caption = name;
                            itemfile.Extension = string.Empty;
                            itemfile.PictureBinary = null; ;
                            itemfile.ResumeId = new Guid(hidResumeId.Value);

                            itemAttachmentService.Create(itemfile);
                            bindList.Add(itemfile);
                        }
                        ts.Complete();
                    }
                }
            }

            gvImageList.DataSource = bindList.OrderBy(m => m.Caption).ThenBy(o=>o.PageNumber);
            gvImageList.DataBind();
            gvImageList.Columns[0].Visible = !ReadOnly;

        }
        #endregion

        #region 保存按钮点击
        /// <summary>
        /// 保存按钮点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonSave_Click(object sender, EventArgs e)
        {
            using (TransactionScope ts = new TransactionScope())
            {
                foreach (GridViewRow gvCurrent in gvImageList.Rows)
                {
                    // 获取控件对象
                    var hidAttachmentId = gvCurrent.FindControl("hidAttachmentId") as HiddenField;
                    var textBoxOrder = gvCurrent.FindControl("textBoxOrder") as TextBox;
                    var textBoxCommon = gvCurrent.FindControl("textBoxCommon") as TextBox;
                    var textBoxPage = gvCurrent.FindControl("textBoxPage") as TextBox;
                    var fileUpload = gvCurrent.FindControl("fileUpload") as FileUpload;

                    // 更新文件列表
                    var itemfile = itemAttachmentService.Retrieve(new Guid(hidAttachmentId.Value));
                    itemfile.Brief = textBoxCommon.Text.Trim();
                    itemfile.Caption = textBoxOrder.Text.Trim();
                    if (!string.IsNullOrWhiteSpace(fileUpload.FileName)) {
                        itemfile.PictureBinary = fileUpload.FileBytes;
                        itemfile.Extension = Path.GetExtension(fileUpload.FileName);
                    }
                    itemfile.PageNumber = CommonHelper.IsValidInt(textBoxPage.Text.Trim());
                    itemAttachmentService.Update(itemfile);
                }
                ts.Complete();
            }
            SearchList();

        }
        #endregion

        protected void gvImageList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var textBoxOrder = e.Row.FindControl("textBoxOrder") as TextBox;
                var lblTitle = e.Row.FindControl("lblTitle") as Label;
                var textBoxCommon = e.Row.FindControl("textBoxCommon") as TextBox;
                var lblCommon = e.Row.FindControl("lblCommon") as Label;
                textBoxOrder.Visible = !ReadOnly;
                lblTitle.Visible = ReadOnly;
                textBoxCommon.Visible = !ReadOnly;

                var textBoxPage = e.Row.FindControl("textBoxPage") as TextBox;
                textBoxPage.Visible = !ReadOnly;
                var lblPageNumber = e.Row.FindControl("lblPageNumber") as Label;
                lblPageNumber.Visible = ReadOnly;
                var fileUpload = e.Row.FindControl("fileUpload") as FileUpload;
                fileUpload.Visible = !ReadOnly;
                lblCommon.Visible = ReadOnly;

                if (!string.IsNullOrEmpty(hidSelectedAttaches.Value))
                {
                    textBoxOrder.Visible = false;
                    lblTitle.Visible = true;
                }
            }
        }

        #region 上传按钮判断
        /// <summary>
        /// 上传按钮判断
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonProgressd_Click(object sender, EventArgs e)
        {
            hiddenFieldDescription.Value = Request.Form["textBoxDescription"];
            hiddenFieldDisplayOrder.Value = Request.Form["textBoxDisplayOrder"];
            hiddenFieldPageNumber.Value = Request.Form["textBoxPageNumber"];
            CurrentFile = HttpContext.Current.Request.Files;

            // 上传前验证

            string checkResult = PageValidate();
            if (!string.IsNullOrWhiteSpace(checkResult))
            {
                messageBox.Show(checkResult);
                return;
            }
            else
            {
                modalPopupExtenderAlert.Show();
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "uploadPostBack", "uploadPostBack();", true);
            }

        }
        #endregion

        #region 上传按钮点击
        /// <summary>
        /// 上传按钮点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonPostBack_Click(object sender, EventArgs e)
        {
            using (TransactionScope ts = new TransactionScope())
            {
                // 获取对象列表
                string[] descriptionList = hiddenFieldDescription.Value.Split(',');
                string[] displayOrderList = hiddenFieldDisplayOrder.Value.Split(',');
                string[] pageNumberList = hiddenFieldPageNumber.Value.Split(',');
                HttpFileCollection files = CurrentFile;
                for (int i = gvImageList.Rows.Count; i < files.Count; i++)
                {
                    HttpPostedFile postedfile = files[i];
                    int rowNumber = i - gvImageList.Rows.Count;
                    if (postedfile.FileName.Length > 0)
                    {
                        // 保存基本信息
                        var itemfile = new Attachement();
                        itemfile.AttachmentId = Guid.NewGuid();
                        itemfile.Brief = descriptionList[rowNumber];
                        itemfile.Caption = displayOrderList[rowNumber];
                        itemfile.Extension = postedfile.ContentType;
                        itemfile.PictureBinary = CommonHelper.StreamToBytes(postedfile.InputStream);
                        itemfile.ResumeId = new Guid(hidResumeId.Value);
                        itemfile.PageNumber = CommonHelper.IsValidInt(pageNumberList[rowNumber].Trim());
                        itemAttachmentService.Create(itemfile);
                    }
                }
                ts.Complete();
            }
            Session.Remove("CurrentFiles");
            SearchList();
        }
        #endregion

        #region 上传前验证

        /// <summary>
        /// 上传前验证

        /// </summary>
        /// <returns>验证结果</returns>
        protected string PageValidate()
        {
            string checkResult = string.Empty;

            // 取出图片列表
            HttpFileCollection files = HttpContext.Current.Request.Files;

            string[] displayOrderList = hiddenFieldDisplayOrder.Value.Split(',');

            // 取出上传限定最大值

            int maxLength = 4194304;
            int checkMax = maxLength / 1024;
            for (int i = 1; i < displayOrderList.Length; i++)
            {
                // 文件不为空

                if (files[i].FileName.Length > 0)
                {
                    // 获取当前文件
                    HttpPostedFile postedfile = files[i];

                    // 判断文件大小
                    if (postedfile.ContentLength > maxLength)
                    {
                        checkResult = Path.GetFileName(postedfile.FileName) + "   必须小于4M";
                        break;
                    }

                    // 判断文件格式
                    string fileExtension = Path.GetExtension(postedfile.FileName).ToUpper(CultureInfo.CurrentCulture);
                    if (!fileExtension.Equals(".JPG", StringComparison.Ordinal) && !fileExtension.Equals(".GIF", StringComparison.Ordinal))
                    {
                        checkResult = Path.GetFileName(postedfile.FileName) + "     必须为gif或者jpg格式";
                        break;
                    }

                    if (string.IsNullOrWhiteSpace(displayOrderList[i]))
                    {
                        checkResult = "必须输入图片标题";
                        break;
                    }


                }
            }

            return checkResult;
        }
        #endregion

        #region 删除按钮点击
        /// <summary>
        /// 删除按钮点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonConfirm_Click(object sender, EventArgs e)
        {
            using (TransactionScope ts = new TransactionScope())
            {
                foreach (GridViewRow gvCurrent in gvImageList.Rows)
                {
                    var checkBoxImageShow = gvCurrent.FindControl("checkBoxImageShow") as CheckBox;
                    if (checkBoxImageShow.Checked)
                    {
                        // 删除文件表

                        var hidAttachmentId = gvCurrent.FindControl("hidAttachmentId") as HiddenField;
                        itemAttachmentService.Delete(new Guid(hidAttachmentId.Value));

                    }
                }
                ts.Complete();
            }

            SearchList();
        }
        #endregion

        #region 关闭按钮点击
        /// <summary>
        /// 关闭按钮点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonClose_Click(object sender, EventArgs e)
        {
            Response.Write("<script>window.opener=true;window.close();</script>");
        }
        #endregion

        protected void button1_Click(object sender, EventArgs e)
        {
            using (TransactionScope ts = new TransactionScope())
            {
                foreach (GridViewRow gvCurrent in gvImageList.Rows)
                {
                    // 获取控件对象
                    var hidAttachmentId = gvCurrent.FindControl("hidAttachmentId") as HiddenField;
                    var fileUpload = gvCurrent.FindControl("fileUpload") as FileUpload;
                    var textBoxCommon = gvCurrent.FindControl("textBoxCommon") as TextBox;
                    var textBoxPage = gvCurrent.FindControl("textBoxPage") as TextBox;

                    if (!string.IsNullOrWhiteSpace(fileUpload.FileName))
                    {
                        // 更新文件列表
                        var itemfile = itemAttachmentService.Retrieve(new Guid(hidAttachmentId.Value));
                        itemfile.PictureBinary = fileUpload.FileBytes;
                        itemfile.Brief = textBoxCommon.Text.Trim();
                        itemfile.PageNumber = CommonHelper.IsValidInt(textBoxPage.Text.Trim());
                        itemAttachmentService.Update(itemfile);
                    }
                }
                ts.Complete();
            }
            SearchList();
        }
    }
}